<!-- 批量编辑 -->
<template>
  <div class="app-container">
    <Edialog
      :outershow="outershow"
      :title="title"
      @saveFn="saveFn"
      @close="closeFn"
      :saveClick="true"
      width="60%"
    >
      <el-row :gutter="20">
        <el-row :gutter="20" class="optionbar">
          <el-col :span="2" style="text-align: center">
            {{ form.subjectSign }}
          </el-col>
          <img
            width="20"
            height="20"
            src="@/assets/icons/fx.png"
            alt=""
            style="margin-right: 5px; cursor: pointer"
            @click="fxchooseFn"
          />
          <img
            width="20"
            height="20"
            src="@/assets/icons/temp.png"
            alt=""
            style="cursor: pointer"
            @click="templatechooseFn"
          />
          <el-col :span="19">
            <el-input
              id="formulainput"
              placeholder=""
              v-model="form.formula"
              :disabled="!isEdit()"
            ></el-input
          ></el-col>

          <!-- <el-tooltip class="item" effect="dark" content="描述" placement="top"> -->
          <i
            style="margin-left: 10px"
            class="el-icon-question"
            @click="tipsOpen = true"
          ></i>
          <!-- 内嵌elementui弹窗 -->
          <el-dialog
            title="说明"
            :visible.sync="tipsOpen"
            width="30%"
            append-to-body
          >
            <!-- html数据回显 -->
            <div v-html="tipsHtml"></div>
          </el-dialog>
          <!-- </el-tooltip> -->
        </el-row>
        <el-col :span="24">
          <SpreadSheet
            style="height: 60vh; width: 100%"
            ref="Sheet"
            SheetName="Sheet1"
            :File="file"
            :Headers="headers"
            :ColumnWidth="200"
            :Records="records"
            @loaded="loaded"
            @cell-selected="cellSelected"
            @cell-edited="cellEdited"
            @change="cellChange"
            :onlyRead="true"
            @initA1="initA1"
          ></SpreadSheet>
        </el-col>
      </el-row>
    </Edialog>
    <subject_choose
      v-if="isShowTempDialog"
      @rowdblclick="rowdblclick"
      ref="subject_choose"
    />
    <fx_choose
      v-if="isShowFxDialog"
      ref="fx_choose"
      @rowdbckick="fxrowdbckick"
    />
    <subject_choose @rowdblclick="rowdblclick" ref="subject_choose" />

    <fx_choose ref="fx_choose" @rowdbckick="fxrowdbckick" />
  </div>
</template>

<script>
import {
  indexToCoord,
  getNonEmptyMergedCells,
  findChangedCells,
  insertTextAtCursor,
} from "@/utils/spreadsheet.js";
import SpreadSheet from "@/components/Xspreadsheet/SpreadSheet.vue";
import Edialog from "@/components/Edialog";
import subject_choose from "@/components/Xspreadsheet/subject_choose.vue";
import fx_choose from "@/components/Xspreadsheet/fx_choose.vue";
import { BsTemplateByIdApi } from "@/api/templateManage";
import { putBatchSaveApi } from "@/api/formulaConfig";
import { getSysCodeByTypeCode } from "@/api/management/code";
export default {
  data() {
    return {
      tipsOpen: false,
      tipsHtml: "",
      isShowTempDialog: false,
      isShowFxDialog: false,
      tableData: [],
      tableLoading: false,
      tableHeight: "calc(60vh - 186px)",

      file: null,
      ColumnCount: 30,
      RowCount: 100,
      headers: [],
      records: [],
      templateType: [
        {
          value: "1",
          label: "类型1",
        },
        {
          value: "2",
          label: "类型2",
        },
      ],
      outershow: false,
      title: "批量编辑",
      form: {
        col: "",
        row: "",
        address: "",
        sAddress: "",
        eAddress: "",
        text: "",
        formula: "",
        excelJson: "",
        templateCode: "",
        subjectSign: "",
      },
      selectionData: [],
      spreadsheetData: [],
      //批量编辑后的数据
      changeSheetData: [],
      //当前选中的cell
      activeCell: {},
      //当前模板id
      templateCode: "",
    };
  },
  components: {
    Edialog,
    SpreadSheet,
    subject_choose,
    fx_choose,
  },
  watch: {
    // "form.text": {
    //   handler(newVal, oldVal) {
    //     // console.log(
    //     //   "newVal:",
    //     //   newVal,
    //     //   this.activeCell,
    //     //   this.activeCell.ri,
    //     //   this.activeCell.ci,
    //     //   xs.sheet.data.getSelectedCell()
    //     // );

    //     // 如果第一个字是等号就用setCell
    //     if (newVal && newVal[0] == "=") {
    //       //去掉等号
    //       this.activeCell.cell.formula = newVal.substring(1);
    //       this.activeCell.cell.text = newVal;

    //       xs.sheet.data.rows.setCell(
    //         this.activeCell.ri,
    //         this.activeCell.ci,
    //         this.activeCell.cell,
    //         "all"
    //       );
    //       setTimeout(() => {
    //         xs.sheet.data.setCellText(
    //           this.activeCell.ri,
    //           this.activeCell.ci,
    //           newVal
    //         );
    //         console.log("xs.sheet.data", xs.sheet.data);
    //       });
    //     } else if (newVal) {
    //       xs.sheet.data.setCellText(
    //         this.activeCell.ri,
    //         this.activeCell.ci,
    //         newVal
    //       );
    //       console.log(2);
    //     } else {
    //       xs.sheet.data.setCellText(this.activeCell.ri, this.activeCell.ci, "");
    //       console.log(3);
    //     }

    //     //设置选中单元格属性
    //     // xs.sheet.data.setSelectedCellAttr('text', newVal);
    //     //设置选中单元格文字
    //     // xs.sheet.data.setSelectedCellText(newVal);
    //     // 强制重绘或更新视图,让表格数据和输入款数据同步
    //     setTimeout(() => {
    //       xs.reRender();
    //     });
    //   },
    // },
    "form.formula": {
      handler(newVal, oldVal) {
        console.log("newVal:", newVal);

        if (newVal || newVal == "") {
          //去掉等号
          this.activeCell.cell.formula = newVal;
          xs.sheet.data.rows.setCell(
            this.activeCell.ri,
            this.activeCell.ci,
            this.activeCell.cell,
            "all"
          );
          this.changeSheetData = this.$cloneDeep([xs.sheet.data.getData()]);
        }
      },
    },
  },
  async created() {
    let res = await getSysCodeByTypeCode("010207001");
    if (res.data && res.data.bcode == 0) {
      this.tipsHtml = res.data.bdata;
    }
  },
  mounted() {},
  computed: {
    // "form.text"() {
    //   return "=" + this.form.text;
    // },
    // "form.formula"() {
    //   return "=" + this.form.formula;
    // },
  },
  methods: {
    /**
     * 在光标位置插入值
     * @param {HTMLInputElement} inputElement - 输入框元素
     * @param {string} value - 要插入的值
     */
    insertValueAtCursor(inputElement, value) {
      // 获取当前光标位置
      const start = inputElement.selectionStart;
      const end = inputElement.selectionEnd;

      // 插入值
      inputElement.value =
        inputElement.value.substring(0, start) +
        value +
        inputElement.value.substring(end);

      // 重新设置光标位置
      inputElement.setSelectionRange(
        start + value.length,
        start + value.length
      );
    },

    //函数模板选择器回调：回显公式
    rowdblclick(row) {
      console.log("函数科目选择器回调：回显公式", row, this.form.formula);
      this.form.templateCode = row.templateCode;
      this.form.excelJson = row.excelJson;
      //如果 this.form.text包括等号，则直接添加函数,否则在最前面加上等号
      if (this.form.formula && this.form.formula.toString().includes("=")) {
        this.form.formula =
          this.form.formula += `'${row.templateCode}'!${row.subjectSign}`;
      } else {
        this.form.formula =
          this.form.formula = `='${row.templateCode}'!${row.subjectSign}`;
      }
      // this.form.text =
      //   this.form.formula += `'${row.templateCode}'!${row.subjectCode}`;
    },
    //函数选择器回调
    fxrowdbckick(row) {
      console.log("函数选择器回调", row, this.form.formula);
      //如果 this.form.text包括等号，则直接添加函数,否则在最前面加上等号
      if (this.form.formula && this.form.formula.toString().includes("=")) {
        this.form.formula = this.form.formula += row.funcCode;
      } else {
        this.form.formula = this.form.formula = "=" + row.funcCode;
      }
    },
    //刚打开表格时初始化数据
    initA1(A1) {
      this.form.address = indexToCoord(0, 0);
      this.form.text = A1 && A1.text;
      console.log("A1", A1);

      this.form.subjectSign = (A1 && A1.subjectSign) || "--";
      this.activeCell = { cell: A1, ri: 0, ci: 0 };
    },
    //单元格是否可编辑
    isEdit() {
      if (this.activeCell && this.activeCell.cell) {
        // 表头不可编辑 不可编辑的不可编辑 数据类型不为数值的不可编辑
        if (
          this.activeCell.cell.isTitle ||
          this.activeCell.cell.editable == false ||
          // this.activeCell.cell.dataType!==2
          !this.activeCell.cell.dataType
        ) {
          return false;
        } else {
          return true;
        }
      }
    },
    fxchooseFn() {
      if (this.isEdit()) {
        this.isShowFxDialog = true;
        this.$nextTick(() => {
          this.$refs.fx_choose.open();
        });
      } else {
        this.$message.warning("该单元格不可编辑");
      }
    },
    templatechooseFn() {
      if (this.isEdit()) {
        this.isShowTempDialog = true;
        this.$nextTick(() => {
          this.$refs.subject_choose.manufacturerOpen();
        });
      } else {
        this.$message.warning("该单元格不可编辑");
      }
    },

    cellEdited(cell, ri, ci) {
      // console.log("cellEdited", cell, ri, ci);
      if (cell && cell.text) {
        this.form.text = cell.text;
      } else if (cell) {
        this.form.text = "";
        // this.form.text = cell;
      } else {
        this.form.text = "";
      }
      this.activeCell = { cell, ri, ci };
    },

    cellSelected(cell, ri, ci) {
      this.selectionData = [];
      console.log("cellSelected", cell, ri, ci);
      this.form.sAddress = "";
      this.form.eAddress = "";
      this.form.address = indexToCoord(ri, ci);
      this.form.address = cell && cell._address;
      this.form.text = cell && cell.text ? cell.text : "";
      this.form.formula = cell && cell.formula ? cell.formula : "";
      this.form.subjectSign = (cell && cell.subjectSign) || "--";
      let celldata = cell ? cell : { text: "" };
      this.activeCell = { cell: celldata, ri, ci };
      this.selectionData = [cell];
    },
    cellChange(data) {
      console.log("cellChange", data);
      this.changeSheetData = this.$cloneDeep(data);
      // xs.sheet.loadData(data);
    },
    //表格数据加载事件
    loaded(spreadsheet) {
      console.log("loaded", spreadsheet);
      if (spreadsheet) {
        this.beforeUpdateSheet = this.$cloneDeep(spreadsheet);
      }
    },
    //外部打开弹窗
    async openFn(scope) {
      console.log(
        "批量编辑",
        scope,
        scope.excelJson,
        JSON.parse(scope.excelJson)
      );
      let res = await BsTemplateByIdApi(scope.templateId);
      if (res.data && res.data.bcode == 0) {
        this.spreadsheetData = JSON.parse(res.data.bdata.excelJson);
        this.templateCode = res.data.bdata.templateCode;
      } else {
        this.spreadsheetData = JSON.parse(scope.excelJson);
        this.templateCode = scope.templateCode;
      }
      //用于修改的数据
      let sheetData = this.$cloneDeep(this.spreadsheetData);
      setTimeout(() => {
        this.$refs.Sheet.loadData(sheetData || []);
      });
      this.outershow = true;
    },
    async saveFn() {
      const changedCells = findChangedCells(
        this.spreadsheetData,
        this.changeSheetData
      );
      console.log(
        "save",
        changedCells,
        this.spreadsheetData,
        this.changeSheetData
      );
      let subjectList = [];
      if (changedCells && changedCells.length > 0) {
        changedCells.forEach((item) => {
          //公式为空的不保存
          // if (item.updatedCell && item.updatedCell.formula) {
          //如果单元格有subjectSign，则直接保存
          let obj = {
            // subjectCode: item.updatedCell.address,
            subjectSign: item.updatedCell.subjectSign,
            formula: item.updatedCell.formula,
          };
          subjectList.push(obj);
          // }
        });
      } else {
        return this.$message.warning("请修改数据后再保存");
      }

      let data = {
        templateCode: this.templateCode,
        excelJson: JSON.stringify(this.changeSheetData),
        subjectList: subjectList,
      };
      console.log("---data", data);
      let res = await putBatchSaveApi(data);
      console.log("---res", res);
      this.$emit("refresh");
      this.closeFn();
    },
    closeFn() {
      this.outershow = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.el-form-item {
  width: 45%;
  // display: flex;
}
::v-deep .el-form-item__content {
  width: 60% !important;
}
.ellipsis_text {
  width: 200px; /* 或者你希望的固定宽度 */
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出容器的文本 */
  text-overflow: ellipsis; /* 使用省略号表示超出容器的文本 */
}
.optionbar {
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f5f6f7;
  border: 1px solid #fff;
  margin: 0 9px !important;
}
</style>
